<!-- art-full-height 自动计算出页面剩余高度 -->
<!-- art-table-card 一个符合系统样式的 class，同时自动撑满剩余高度 -->
<template>
  <div class="art-full-height">
    <BasicCard>
      <BasicVxeForm
        ref="formRef"
        :formOptions="formOptions"
        :searchLoading="gridOptions.loading"
        @search="getData"
        @reset="getData"
      >
      </BasicVxeForm>
    </BasicCard>

    <BasicCard class="art-table-card">
      <BasicVxeTable ref="gridRef" v-bind="gridOptions">
        <template #title_left>
          <el-button plain type="primary" icon="Plus" @click="handleClickAdd">添加员工</el-button>
        </template>

        <template #tools_left>
          <a
            href="https://jwesystem.oss-cn-beijing.aliyuncs.com/renYuanMoBan.xlsx"
            download="人员导入模版.xlsx"
            style="margin-right: 20px; color: #2785f8; text-decoration: underline"
            >下载人员导入模版</a
          >
        </template>

        <template #action="{ row }">
          <el-button type="primary" link @click="handleClickEdit(row)">编辑</el-button>
          <el-divider direction="vertical" />
          <el-button
            :type="!row.wxClubOpenId ? 'primary' : 'danger'"
            link
            @click="handleClickBind(row)"
            >{{ !row.wxClubOpenId ? '绑定公众号' : '解绑公众号' }}</el-button
          >
          <el-divider direction="vertical" />
          <el-button type="primary" link @click="handleClickDel(row)">删除</el-button>
        </template>
      </BasicVxeTable>
    </BasicCard>

    <AddForm ref="addForm" :gongZhongList="gongZhongList" @success="getData"></AddForm>
    <BindModal @register="registerModal" @hide="getData" />
  </div>
</template>

<script setup lang="ts">
  import { clone } from 'xe-utils'
  import { useVxeModal } from '@/components/ui/vxe-modal'
  import { columns, searchFormItems } from './data'
  import AddForm from './components/AddForm.vue'
  import BindModal from './components/BindModal.vue'
  import { getGongZhongHuoQu } from '@/api/gongGongChaXun'
  import {
    GetUserList,
    deleteTicket,
    deleteYuanGong,
    type GetUserListResult
  } from '@/api/persondocument'
  // import { postDaoRuRenYuanXinXi } from '@/api/personAdmin'

  interface FormV0 {
    employeeCode: string
    firstName: string
    jobTitleId: string
    gender: string
    nationId: string
    state: string
  }

  const { t } = useI18n()
  const [registerModal, modalMethods] = useVxeModal()

  const addForm = ref<InstanceType<typeof AddForm>>()
  const gongZhongList = ref<LabelValueOption[]>([])

  // 获取工种列表
  const getGongZhongList = () => {
    getGongZhongHuoQu('')
      .then((val) => {
        const item = formRef.value?.getItemByField('gongGongId')
        if (item) {
          const options = val.map((item) => {
            return { label: item.title, value: item.id }
          })
          gongZhongList.value = [...options]

          options.unshift({ label: '全部', value: '0' })

          item.itemRender.options = options
        }
      })
      .catch((error) => {
        console.error(error)
      })
  }

  const getData = async () => {
    try {
      const data = formRef.value!.getFormData()

      gridOptions.loading = true
      // formOptions.loading = true
      const res = await GetUserList({
        employeeCode: data.employeeCode,
        firstName: data.firstName,
        nationId: data.nationId,
        gender: data.gender,
        state: data.state,
        jobtitleid: data.gongGongId == 0 ? '' : data.gongGongId
      })
      gridOptions.data = res.map((v) => ({
        ...v
        // birthDay: dayjs(v.birthDay).format('YYYY-MM-DD'),
        // hireDate: dayjs(v.hireDate).format('YYYY-MM-DD'),
        // dimissionDate: dayjs(v.hireDate).format('YYYY-MM-DD')
      }))
    } catch (error) {
      console.error(error)
    } finally {
      gridOptions.loading = false
    }
  }

  const handleClickAdd = () => {
    addForm.value?.openDrawer(true, { type: 'add' })
  }

  const handleClickEdit = (row: GetUserListResult) => {
    addForm.value?.openDrawer(true, { type: 'edit', row: clone(row, true) })
  }

  const handleClickDel = (row: GetUserListResult) => {
    ElMessageBox({
      title: '删除确认',
      message: `删除该员工，该员工的员工绩效也会一起删除，确定删除员工<strong style="font-weight: bold">${row.firstName}</strong>吗？`,
      type: 'warning',
      showCancelButton: true,
      dangerouslyUseHTMLString: true,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          deleteYuanGong(row.id)
            .then(() => {
              ElMessage.success(t('system.成功', { action: t('system.删除') }))
              done()
              // 完成后刷新数据
              getData()
            })
            .catch((error) => {
              ElMessage.error(t('system.失败', { action: t('system.删除') }))
              console.error(error)
            })
            .finally(() => {
              instance.confirmButtonLoading = false
            })
        } else {
          done()
        }
      }
    })
  }

  const handleClickBind = (row: GetUserListResult) => {
    if (!row.wxClubOpenId) {
      // 绑定
      modalMethods.openModal(true, {
        row
      })
    } else {
      ElMessageBox({
        title: '解绑',
        message: `您确认要解绑 <strong style="font-weight: bold">${row.firstName}</strong >吗？`,
        type: 'warning',
        showCancelButton: true,
        dangerouslyUseHTMLString: true,
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            deleteTicket(row.id)
              .then(() => {
                ElMessage.success(t('system.成功', { action: t('system.解绑') }))
                done()

                // 直接更新
                row.wxClubOpenId = ''
                // 完成后刷新数据
                // getData()
              })
              .catch((error) => {
                ElMessage.error(t('system.失败', { action: t('system.解绑') }))
                console.error(error)
              })
              .finally(() => {
                instance.confirmButtonLoading = false
              })
          } else {
            done()
          }
        }
      })
    }
  }

  const formRef = ref<BasicFormInstance>()
  const formOptions = reactive<BasicFormProps<FormV0>>({
    data: {
      state: '0',
      gongGongId: '0'
    },
    items: searchFormItems
  })

  const gridRef = ref<BasicGridInstance>()
  const gridOptions = reactive<BasicGridProps<GetUserListResult>>({
    extraConfig: {
      isCustom: true,
      isExport: true,
      isFilterAndSort: true
    }, // 拓展的配置
    id: `personAdmin-dangAnGuanLi`, // id用于缓存,务必配置
    height: 'auto',
    columns,
    toolbarConfig: {}, // 工具栏
    exportConfig: {
      filename: t('export.员工档案')
    }
  })

  onMounted(() => {
    getGongZhongList()
    getData()
  })
</script>

<style lang="scss" scoped></style>
